<template>
  <div class="tags-view-out">
    <div id="tags-view-container" class="tags-view-container">
      <scroll-pane ref="scrollPane" class="tags-view-wrapper" @scroll="handleScroll">
        <router-link
          v-for="(tag,index) in visitedViews"
          ref="tag"
          :key="tag.path"
          :class="isActive(tag)?'active':''"
          :to="{ path: tag.path, query: tag.query, fullPath: tag.fullPath }"
          tag="span"
          class="tags-view-item"
          @click.middle.native="!isAffix(tag)?closeSelectedTag(tag):''"
          @contextmenu.prevent.native="openMenu(tag,$event)"
          :style="{width: isOver && index !==0 && !isActive(tag) ? '102px' : 'auto'}"
          >
          <div v-if="index !== 0"></div>
          {{ tag.title }}
          <span v-show="!isAffix(tag)" class="el-icon-close" @click.prevent.stop="closeSelectedTag(tag)" />
        </router-link>
      </scroll-pane>
    </div>
  </div>
</template>

<script>
import ScrollPane from './ScrollPane'
import path from 'path'
import {mapGetters} from "vuex";
export default {
  components: { ScrollPane },
  name: "Tags",
  data() {
    return {
      visible: false,
      top: 0,
      left: 0,
      selectedTag: {},
      affixTags: [],
      isOver: false
    }
  },
  computed: {
    ...mapGetters(["menu", 'userInfo']),
    visitedViews() {
      return this.$store.state.tagsView.visitedViews
    },
    routes() {
      return this.menu
    },

  },
  watch: {
    $route() {
      this.addTags()
      this.moveToCurrentTag()
    },
    visible(value) {
      if (value) {
        document.body.addEventListener('click', this.closeMenu)
      } else {
        document.body.removeEventListener('click', this.closeMenu)
      }
    }
  },
  mounted() {
    this.initTags()
    this.addTags()
  },
  methods: {
    isActive(route) {
      return route.path === this.$route.path
    },
    isAffix(tag) {
      return tag.meta && tag.meta.affix
    },
    filterAffixTags(routes, basePath = '/') {
      let tags = []
      routes.forEach(route => {
        if (route.name && route.hasChildren) {
          const tagPath = path.resolve(basePath, route.path)
          tags.push({
            fullPath: tagPath,
            path: tagPath,
            name: route.name,
            meta: { ...route.meta }
          })
        }
        if (route.children) {
          const tempTags = this.filterAffixTags(route.children, route.path)
          if (tempTags.length >= 1) {
            tags = [...tags, ...tempTags]
          }
        }
      })
      return tags
    },
    initTags() {
      const affixTags = this.affixTags = this.filterAffixTags(this.routes)
      for (const tag of affixTags) {
        // Must have tag name
        if (tag.name && tag.path.indexOf(this.$route.path.split('/')[1]) > -1) {
          this.$store.dispatch('tagsView/addVisitedView', tag)
        }
      }
    },
    addTags() {
      const { name } = this.$route
      if (name) {
        this.$store.dispatch('tagsView/addView', this.$route)
      }
      this.computeWidth()
      return false
    },
    moveToCurrentTag() {
      const tags = this.$refs.tag
      this.$nextTick(() => {
        for (const tag of tags) {
          if (tag.to.path === this.$route.path) {
            this.$refs.scrollPane.moveToTarget(tag)
            // when query is different then update
            if (tag.to.fullPath !== this.$route.fullPath) {
              this.$store.dispatch('tagsView/updateVisitedView', this.$route)
            }
            break
          }
        }
      })
    },
    refreshSelectedTag(view) {
      this.$store.dispatch('tagsView/delCachedView', view).then(() => {
        const { fullPath } = view
        this.$nextTick(() => {
          this.$router.replace({
            path: '/redirect' + fullPath
          })
        })
      })
    },
    closeSelectedTag(view) {
      this.$store.dispatch('tagsView/delView', view).then(({ visitedViews }) => {
        if (this.isActive(view)) {
          this.toLastView(visitedViews, view)
        }
      })
    },
    closeOthersTags() {
      this.$router.push(this.selectedTag)
      this.$store.dispatch('tagsView/delOthersViews', this.selectedTag).then(() => {
        this.moveToCurrentTag()
      })
    },
    closeAllTags(view) {
      this.$store.dispatch('tagsView/delAllViews').then(({ visitedViews }) => {
        if (this.affixTags.some(tag => tag.path === view.path)) {
          return
        }
        this.toLastView(visitedViews, view)
      })
    },
    toLastView(visitedViews, view) {
      const latestView = visitedViews.slice(-1)[0]
      if (latestView) {
        this.$router.push(latestView.fullPath)
      } else {
        // now the default is to redirect to the home page if there is no tags-view,
        // you can adjust it according to your needs.
        if (view.name === 'Dashboard') {
          // to reload home page
          this.$router.replace({ path: '/redirect' + view.fullPath })
        } else {
          this.$router.push('/')
        }
      }
    },
    openMenu(tag, e) {
      const menuMinWidth = 105
      const offsetLeft = this.$el.getBoundingClientRect().left // container margin left
      const offsetWidth = this.$el.offsetWidth // container width
      const maxLeft = offsetWidth - menuMinWidth // left boundary
      const left = e.clientX - offsetLeft + 15 // 15: margin right

      if (left > maxLeft) {
        this.left = maxLeft
      } else {
        this.left = left
      }

      this.top = e.clientY
      this.visible = true
      this.selectedTag = tag
    },
    closeMenu() {
      this.visible = false
    },
    handleScroll() {
      this.closeMenu()
    },
    // 计算导航菜单宽度
    computeWidth() {
      this.isOver = false
      this.$nextTick(()=>{
        let nodeList = document.querySelectorAll('.tags-view-item')
        let width = 0;
        Array.from(nodeList).forEach(item => {
          width += item.clientWidth
        })
        this.isOver = width > 1720
      })
    }
  }
}
</script>

<style lang="less" scoped>
.tags-view-container {
  height: 32px;
  width: calc(100vw - 200px);
  margin: 0 0 0 200px;
  position: relative;
  bottom: 32px;
  .tags-view-wrapper {
    height: 32px;
    .tags-view-item {
      cursor: pointer;
      display: inline-block;
      position: relative;
      height: 32px;
      padding: 6px 30px 6px 17px;
      font-size: 18px;
      font-weight: bold;
      color: white;
      line-height: 25px;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
      word-break: break-all;
      &:nth-child(1) {
        padding: 6px 17px;
      }
      > div:nth-child(1) {
        height: 23px;
        width: 0px;
        border: 1px solid white;
        float: left;
        margin-left: -17px;
      }
      > span:nth-child(2) {
        cursor: pointer;
        display: none;
        position: absolute;
        right: 4px;
        top: 7px;
        font-size: 20px;
      }
      &:hover {
        > span:nth-child(2) {
          display: inline-block;
        }
      }
      &.active {
        background: #fff;
        color: #004CA7;
        border-radius: 4px 4px 0px 0px;
        > span:nth-child(2) {
          display: inline-block;
        }
      }
      &.active + span {
        > div:nth-child(1) {
          border: none;
        }
      }
    }
  }
}
</style>

<style lang="scss">
</style>
